package com.zretc.demojparedis.service.impl;

import com.zretc.demojparedis.dao.QuestionDao;
import com.zretc.demojparedis.entity.Question;
import com.zretc.demojparedis.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.LockModeType;

@Service
@Transactional
public class QuestionServiceImpl implements QuestionService {

    //注入一个dao
    @Autowired
    private QuestionDao questionDao;

    @Override
    //@Cacheable(cacheNames = "com.zretc.demojparedis.service.getquestion")
    public Page<Question> getQuestionByPage(String keywords, int page, int pagesize) {
        //page和pagesize的条件判断
        if (page < 1) {
            page = 1;
        }
        //-1是因为我们的PageRequest的参数是从0开始，0表示第一页
        Pageable pageable = PageRequest.of(page - 1, pagesize);
        Page<Question> pg = questionDao.getQuestionByPage(keywords, pageable);
        return pg;
    }

   // @CachePut(key = "#question.qid", cacheNames = "getQuestionById")
    @Override
    public Question updateQuestion(Question question) {
        questionDao.saveAndFlush(question);
        return question;
    }


    //@Cacheable(key = "#qid", cacheNames = "getQuestionById")
    @Override
    public Question getQuestionById(int qid) {
        return questionDao.findById(qid).get();
    }


    /**
     * 悲观锁的测试
     *
     * @param question
     * @return
     */
    public Question updateQuestionlock(Question question) {
        questionDao.saveAndFlush(question);
        return question;
    }

    /**
     * 查询单个question对象,悲观锁的测试1
     *
     * @param qid
     * @return
     */
    @Transactional
    public Question getQuestionByIdlock(int qid) {
        Question question = questionDao.getQuestionByIdlock(qid);

        question.setQtitle("悲观锁测试00"+Math.random());
        //查询后调用save的方法
        questionDao.saveAndFlush(question);
        return question;
    }

    /**
     * 查询单个question对象,悲观锁的测试2
     *
     * @param qid
     * @return
     */
    @Transactional
    public Question getQuestionByIdlock2(int qid) {
        Question question = questionDao.getQuestionByIdlock(qid);

        question.setQtitle("悲观锁测试02"+Math.random());

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //查询后调用save的方法
        questionDao.saveAndFlush(question);
        return question;
    }


}
